﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;

using Microsoft.Reporting.WebForms;
using System.IO;

using KPIReport.Web.Support;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace KPIReport.Web.usercontrols
{
	public partial class ReportViewer : UserControl
	{

		private const string VS_MAXPAGE = "MaximumPage";
		private const string VS_CURRENTPAGE = "CurrentPage";
		private const string VS_PAGESIZE = "PageSize";

		public int PageSize
		{
			get
			{
				return (ViewState[VS_PAGESIZE] == null) ? 5 : (Convert.ToInt32(ViewState[VS_PAGESIZE]));
			}

			set
			{
				ViewState[VS_PAGESIZE] = value;
			}
		}

		public int CurrentPage
		{
			get
			{
				return (ViewState[VS_CURRENTPAGE] == null) ? 1 : ((Convert.ToInt32(ViewState[VS_CURRENTPAGE]) < 1) ? 1 : (Convert.ToInt32(ViewState[VS_CURRENTPAGE])));
			}
			set
			{
				ViewState[VS_CURRENTPAGE] = value;
				lblCurrentPage.Text = value.ToString();
			}

		}

		public Unit Width
		{
			get
			{
				return rptViewer.Width;
			}
			set
			{
				rptViewer.Width = value;
			}
		}

		public Unit Height
		{
			get
			{
				return rptViewer.Height;
			}

			set
			{
				rptViewer.Height = value;
			}
		}

		public int MaxPage
		{
			get
			{
				return (ViewState[VS_MAXPAGE] == null) ? 1 : (Convert.ToInt32(ViewState[VS_MAXPAGE]));
			}
			set
			{
				ViewState[VS_MAXPAGE] = value;
				lblTotalPages.Text = value.ToString();
			}

		}


		private bool _hasData;
		public bool HasData
		{
			set
			{
				_hasData = value;
				pnlNoDataFound.Visible = !value;
				rptViewer.Visible = value;
			}

		}

		protected void imbGoTo_Click(object sender, ImageClickEventArgs e)
		{
			if (!string.IsNullOrEmpty(txtNewPage.Text))
			{
				if (Helper.IsNumber(txtNewPage.Text, System.Globalization.NumberStyles.Integer, Helper.Culture.English))
				{
					CurrentPage = Convert.ToInt32(txtNewPage.Text);
					FormButton(CurrentPage, MaxPage);
				}
			}

		}

		protected void imbSearch_Click(object sender, ImageClickEventArgs e)
		{
            rptViewer.Find(txtSearch.Text, 1);

		}

		protected void ddlView_SelectedIndexChanged(object sender, EventArgs e)
		{

		}

		protected void imbFirst_Click(object sender, ImageClickEventArgs e)
		{
			CurrentPage = 1;
			FormButton(CurrentPage, MaxPage);

		}

		protected void imbPrev_Click(object sender, ImageClickEventArgs e)
		{
			CurrentPage -= 1;
			FormButton(CurrentPage, MaxPage);

		}

		protected void imbNext_Click(object sender, ImageClickEventArgs e)
		{
			CurrentPage += 1;
			FormButton(CurrentPage, MaxPage);

		}

		protected void imbLast_Click(object sender, ImageClickEventArgs e)
		{
			CurrentPage = MaxPage;
			FormButton(CurrentPage, MaxPage);

		}

		private void ButtonEnability(bool first, bool prev, bool next, bool last)
		{
			imbFirst.Enabled = first;
			imbPrev.Enabled = prev;
			imbNext.Enabled = next;
			imbLast.Enabled = last;

		}

		protected void btnExport_Click(object sender, EventArgs e)
		{
			if (ddlExportType.SelectedValue == "-1")
			{
                //Functions.Web.Alert(this.Page, "Please select a format file");
				return;
			}

			string format = ddlExportType.SelectedValue;

			Warning[] warnings;
			string[] streamids;
			string mimeType;
			string encoding;
			string extension;

			byte[] bytes;

			string strFilePath = string.Empty;

			switch (format.ToLower())
			{
				case ("excel"):

					bytes = rptViewer.LocalReport.Render(
						 "Excel", null, out mimeType, out encoding,
							out extension,
						 out streamids, out warnings);

                    strFilePath = rptViewer.LocalReport.DisplayName + ".xls";

					Response.AppendHeader("content-disposition", "attachment;filename=" + strFilePath);
					Response.BinaryWrite(bytes);
					Response.End();

					break;
				case ("pdf"):

					bytes = rptViewer.LocalReport.Render(
						 "Pdf", null, out mimeType, out encoding,
							out extension,
						 out streamids, out warnings);

                    strFilePath = rptViewer.LocalReport.DisplayName + ".pdf";

					Response.AppendHeader("content-disposition", "attachment;filename=" + strFilePath);
					Response.BinaryWrite(bytes);
					Response.End();

					break;
			}
		}

		protected void imbRefresh_Click(object sender, ImageClickEventArgs e)
		{
			rptViewer.LocalReport.Refresh();

		}

		protected void imbPrint_Click(object sender, ImageClickEventArgs e)
		{
            Warning[] warnings;
            string[] streamids;
            string mimeType;
            string encoding;
            string extension;

            byte[] bytes = rptViewer.LocalReport.Render("PDF", null, out mimeType,
                           out encoding, out extension, out streamids, out warnings);

            MemoryStream ms = new MemoryStream();
            ms.Write(bytes, 0, bytes.Length);
            // Set the position to the beginning of the stream.
            ms.Seek(0, System.IO.SeekOrigin.Begin);

            //Open exsisting pdf
            Document document = new Document(iTextSharp.text.PageSize.LETTER);
            PdfReader reader = new PdfReader(bytes);
            //Getting a instance of new pdf wrtiter
            PdfWriter writer = PdfWriter.GetInstance(document, ms);
            document.Open();
            PdfContentByte cb = writer.DirectContent;

            int i = 0;
            int p = 0;
            int n = reader.NumberOfPages;
            Rectangle psize = reader.GetPageSize(1);

            float width = psize.Width;
            float height = psize.Height;

            //Add Page to new document
            while (i < n)
            {
                document.NewPage();
                p++;
                i++;

                PdfImportedPage page1 = writer.GetImportedPage(reader, i);
                cb.AddTemplate(page1, 0, 0);
            }

            //Attach javascript to the document
            PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer);
            writer.AddJavaScript(jAction);
            document.Close();

            string strFilePath = string.IsNullOrEmpty(rptViewer.LocalReport.DisplayName) ? "Print.pdf" : rptViewer.LocalReport.DisplayName;

            Response.ContentType = "application/pdf";
            Response.AppendHeader("content-disposition", "attachment;filename=" + strFilePath);
            Response.BinaryWrite(ms.ToArray());
            Response.End();

		}

		protected void ddlPageWidth_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (ddlPageWidth.SelectedIndex != 0)
			{
				switch (ddlPageWidth.SelectedValue)
				{
					case ("1"):
						rptViewer.ZoomMode = ZoomMode.PageWidth;
						break;
					case ("2"):
						rptViewer.ZoomMode = ZoomMode.FullPage;
						break;
					default:
						rptViewer.ZoomMode = ZoomMode.Percent;
						rptViewer.ZoomPercent = Convert.ToInt32(ddlPageWidth.SelectedValue);
						break;
				}
			}
		}

		private void FormButton(int currentPage, int maxPage)
		{
			if (currentPage > 1) // if CurrentPage is greater than 1
			{
				if (currentPage == maxPage)
					ButtonEnability(true, true, false, false);
				else
					ButtonEnability(true, true, true, true);
			}
			else
			{
				if (currentPage == maxPage)
					ButtonEnability(false, false, false, false);
				else
					ButtonEnability(false, false, true, true);
			}

		}

	}


}